package DBtil;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;

public class DBtil1 {
    //数据源
    private  static DataSource dataSource=null;
    //数据库连接串
    private static final String URL="jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8" +
            "&allowPublicKeyRetrieval=true&useSSL=false";
    //用户名
    private static final String USER="root";
    //密码
    private static final String PASSWORD="123456";

    //定义连接对象
    Connection connection=null;
    //定义处理SQL执行对象
    Statement statement=null;//执行静态输入，存在sql注入问题
    //定义结果集对象
    ResultSet resultSet=null;
    //当类加载到JVM的时候，执行数据源的初始化
    static {
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PASSWORD);
        dataSource=mysqlDataSource;
    }
    //构造私有化，防止new这个对象
    private DBtil1(){

    }
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    public static void close(ResultSet resultSet,Statement statement,Connection connection){
        //依次释放资源，关闭链接
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
